import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
// 响应式表单
import { FormBuilder, FormControl, FormGroup, MaxLengthValidator, ValidationErrors, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { EmployeeServiceSvr } from '../../../services/employee.service'
import { SalaryMgeSvr } from '../../../services/salary-mge.service'
import { ConstantPool } from '@angular/compiler';

@Component({
  selector: 'app-salary-manage',
  templateUrl: './salary-manage.component.html',
  styleUrls: ['./salary-manage.component.less']
})
export class SalaryManageComponent implements OnInit {

  @Output() cancelDetailFileShowModal = new EventEmitter();

  // id
  EmpId:string
  // 增加模态框
  isVisible = false;
  // 增加需要的 -修改前工资
  beforeSalary:any;
  // 薪资表格模拟数据
  listOfData:any = [];

  constructor(
    private modal: NzModalService,
    private employSvr: EmployeeServiceSvr,    
    private SalaryMgeSvr: SalaryMgeSvr,
    private fb: FormBuilder
    ) { 
      // 增加 - 响应式表单
      this.validateForm = this.fb.group({
        oldSalary: [{value: this.beforeSalary, disabled: true}],
        NewSalary: [null, [Validators.required ,this.numberValidator]],
        ChangeReason: ['', [Validators.required]]
      });
    }

  // 校验数字  -- 非0的正整数
  numberValidator(value):any{
    var myreg=/^\d+$/;
    let valid=myreg.test(value.value);
    return valid?null:{NewSalary:true};
  }
  
  // 增加
  showModal(): void {
    this.isVisible = true;
  }
  
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  // 增加的响应式表单
  validateForm: FormGroup;
  testId:number = 10;

  submitForm(value: { NewSalary:string, ChangeReason:string }): void {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    this.isVisible = false;
    this.testId ++;
    this.SalaryMgeSvr.addSalaryRecord(this.EmpId,this.beforeSalary,Number(value.NewSalary),value.ChangeReason).then(res => {
      // 重新排序
      this.getAll()
    })
  }

  // 返回上一级
  back(): void {
    this.cancelDetailFileShowModal.emit();
    window.sessionStorage.setItem('index', '-1');
  }

  getAll() {
    console.log('this.EmpId=', this.EmpId);
    this.employSvr.getArchivesByEmpId(this.EmpId).then(res => {
      this.listOfData = res.SalaryDto.SalaryRecords
      // 获取当前最新的工资
      this.beforeSalary =res.SalaryDto.SalaryRecords[0].NewSalary
    })
  }

  // 获取所有最新消息
  ngOnInit(): void {
    // 初始化数据
    this.EmpId = window.sessionStorage.getItem('sendEnterFilesID');
    this.getAll()
  }
}

